using System;
using JetBrains.Annotations;
using LiteNetLib;
using UnityEngine;
using UnityEngine.UI;

public class LoginUI : MonoBehaviour
{
    [SerializeField] private InputField ServerIP, ServerPort;
    [SerializeField] private InputField UserName, UserPasswd;

    public Action<string, int, string, string> ActionLogin = null;

    private void Awake()
    {
        ServerIP.text = PlayerPrefs.GetString("server_ip", "faceswap.mobi");
        ServerPort.text = PlayerPrefs.GetString("server_port", "10082");
        UserName.text = PlayerPrefs.GetString("user_name", "");
        UserPasswd.text = PlayerPrefs.GetString("user_passwd", "");
    }

    public void OnLogin()
    {
        if (ActionLogin == null)
        {
            NetDebug.Log("无法执行~");
            return;
        }

        var ip = ServerIP.text;
        var name = UserName.text;
        var passwd = UserPasswd.text;

        if (string.IsNullOrEmpty(ip))
        {
            NetDebug.Log("IP地址没写~");
            return;
        }

        if (string.IsNullOrEmpty(name))
        {
            NetDebug.Log("名字没写~");
            return;
        }

        if (string.IsNullOrEmpty(passwd))
        {
            NetDebug.Log("密码没写~");
            return;
        }

        if (!int.TryParse(ServerPort.text, out var port) && (port < 1024 || port > 20000))
        {
            NetDebug.Log("端口需要在1024~20000的范围内");
            return;
        }

        PlayerPrefs.SetString("server_ip", ip);
        PlayerPrefs.SetString("server_port", ServerPort.text);
        PlayerPrefs.SetString("user_name", name);
        PlayerPrefs.SetString("user_passwd", passwd);
        ActionLogin(ip, port, name, passwd);
    }
}
